<?php
/**
 * Created by PhpStorm.
 * User: 六花
 * Date: 2019/4/27
 * Time: 17:20
 */

namespace Api\Controller;

use Think\Controller;


class GoodsController extends Controller {

    public  function  __construct()
    {

    }

    public function editGoods(){
        //        $_POST = json_decode($rs,true);
        $GLOBALS['HTTP_RAW_POST_DATA'] = stripslashes($GLOBALS['HTTP_RAW_POST_DATA']);
//        $rss = htmlspecialchars_decode($GLOBALS['HTTP_RAW_POST_DATA']);
//        $GLOBALS['HTTP_RAW_POST_DATA'] = str_replace('\','',$GLOBALS['HTTP_RAW_POST_DATA']);
        $GLOBALS['HTTP_RAW_POST_DATA'] = str_replace('"[','[',$GLOBALS['HTTP_RAW_POST_DATA']);
        $GLOBALS['HTTP_RAW_POST_DATA'] = str_replace(']"',']',$GLOBALS['HTTP_RAW_POST_DATA']);
        $_POST = json_decode($GLOBALS['HTTP_RAW_POST_DATA'],true);

//        var_dump($GLOBALS['HTTP_RAW_POST_DATA']);exit;
        if(!$_POST || !is_array($_POST)){
            $return_array = array(
                'MessageCode' => 2,
                'Message' => '参数错误'
            );
            echo json_encode($return_array,JSON_UNESCAPED_UNICODE);
            exit;
        }

        $goods_model = M('goods');
        $spec_model = M('goods_spec');
        $brand_model = M('brand');
        $country_model = M('country_info');
        $unit_model = M('unit');
        $wrap_model = M('wrap');
        $tax_model = M('my_tax');
        $stock_model = M('storestock');
        $store_model = M('store');

        if(!$_POST['ProductItems'] || !is_array($_POST['ProductItems'])){
            $return_array = array(
                'Sku' => '',
                'Field' => 'ProductItems',
                'Msg' => '参数错误',
                "Result" => 0
            );
            echo json_encode($return_array,JSON_UNESCAPED_UNICODE);
            exit;
        }
        $send_array = array();
        $pic_array = array();

        foreach ($_POST['ProductItems'] as $key => $value){


//            商品查询
            $res = $goods_model -> where(array('sku'=>$value['Sku'])) -> find();

            if(!$res){
                $send_array[] = array(
                    'Sku' => $value['Sku'],
                    'Field' => 'ProductItems',
                    'Msg' => '商品查询失败',
                    "Result" => 0
                );
                continue;
            }


            //logo
            $temp_logo = trim($value['Manufacturer']);
            if($temp_logo){
                $res_logo = $brand_model -> where(array('brand_name'=>$temp_logo)) -> find();
                if(!$res_logo){
                    $logo_add = $brand_model -> add(array('brand_name'=>$temp_logo));
                    if(!$logo_add){
                        $send_array[] = array(
                            'Sku' => $value['Sku'],
                            'Field' => 'Manufacturer',
                            'Msg' => '品牌添加失败',
                            "Result" => 0
                        );
                        continue;
                    }
                }
            }

            //出产地
            $temp_country = $country_model -> where(array('country_code'=>$value['CountryId'])) ->find();
            if(!$temp_country){
                $send_array[] = array(
                    'Sku' => $value['Sku'],
                    'Field' => 'CountryId',
                    'Msg' => '出产地查询失败',
                    "Result" => 0
                );
                continue;
            }
            //单位
            $temp_unit = $unit_model -> where(array('unit_code'=>$value['UnitId'])) ->find();
            if(!$temp_unit){
                $send_array[] = array(
                    'Sku' => $value['Sku'],
                    'Field' => 'CountryId',
                    'Msg' => '出产地查询失败',
                    "Result" => 0
                );
                continue;
            }

            //包装

            $temp_wrap = $wrap_model -> where(array('wrap_code'=>$value['WrapId'])) ->find();

            if(!$temp_wrap){
                $send_array[] = array(
                    'Sku' => $value['Sku'],
                    'Field' => 'WrapId',
                    'Msg' => '包装查询失败',
                    "Result" => 0
                );
                continue;
            }

            //税率
            $consolidated_tax = get_consolidated_tax($value['ConsumptionTaxRate'],$value['VATRate']);
            $r['add_tax'] = $value['VATRate'];
            $r['consumption_tax'] = $value['ConsumptionTaxRate'];
            $temp_tax = $tax_model -> where(array('consumption_tax'=>$r)) ->find();

            if(!$temp_tax){
                $rx['add_tax'] = $value['VATRate'];
                $rx['consumption_tax'] = $value['ConsumptionTaxRate'];
                $rx['consolidated_tax'] = $value['consolidated_tax'];
                $rx['tax_name'] = '消费税为'.$value['ConsumptionTaxRate'].'的商品';
                $rx['consolidated_tax'] = $consolidated_tax;
                $add_tax = $tax_model -> add($rx);
                if(!$add_tax){
                    $send_array[] = array(
                        'Sku' => $value['Sku'],
                        'Field' => 'ConsumptionTaxRate',
                        'Msg' => '税率查询失败',
                        "Result" => 0
                    );
                    continue;
                }
                $tax_id = $add_tax;
            }else{
                $tax_id = $temp_tax['tax_id'];
                $consolidated_tax = $temp_tax['consolidated_tax'];
            }
            //店铺
            $resStore = $store_model -> where(array('store_id'=>$value['VendorId'])) -> find();
            if(!$resStore){
                $send_array[] = array(
                    'Sku' => $value['Sku'],
                    'Field' => 'VendorId',
                    'Msg' => '店铺查询失败',
                    "Result" => 0
                );
                continue;
            }

            if(!$temp_tax){
                $rx['add_tax'] = $value['VATRate'];
                $rx['consumption_tax'] = $value['ConsumptionTaxRate'];
                $rx['consolidated_tax'] = $value['consolidated_tax'];
                $rx['tax_name'] = '消费税为'.$value['ConsumptionTaxRate'].'的商品';
                $rx['consolidated_tax'] = $consolidated_tax;
                $add_tax = $tax_model -> add($rx);
                if(!$add_tax){
                    $send_array[] = array(
                        'Sku' => $value['Sku'],
                        'Field' => 'ConsumptionTaxRate',
                        'Msg' => '税率查询失败',
                        "Result" => 0
                    );
                    continue;
                }
                $tax_id = $add_tax;
            }else{
                $tax_id = $temp_tax['tax_id'];
                $consolidated_tax = $temp_tax['consolidated_tax'];
            }
            //收到的数据有规格
            if($value['SpecItems'] && is_array($value['SpecItems'])) {

                //先删除规格

                $skus_arr = _array_column((array)$_POST['ProductItems'][$key]['SpecItems'],'Sku');

                //数组转字符串
                $skus_str = implode($skus_arr,',');
                $temp['sku'] = array('not in',$skus_str);
                $temp['goods_id'] = $res['goods_id'];
                $res_remove = M('goods_spec')->where($temp)->delete();
                //只删除不添加
                if($res_remove === false){
                    $send_array[] = array(
                        'Sku' => $value['Sku'],
                        'Field' => '',
                        'Msg' => '删除原规格失败',
                        "Result" => 0
                    );
                    continue;
                }
                foreach ($_POST['ProductItems'][$key]['SpecItems'] as $k => $v){
                    //仓库
                    $res_stock = $stock_model -> where(array('storestock_id'=>$value['VendorId'].$v['CustomsChannelId'])) -> find();

                    if(!$res_stock){
                        $send_array[] = array(
                            'Sku' => $value['Sku'],
                            'Field' => 'CustomsChannelId',
                            'Msg' => '查询报关通道失败',
                            "Result" => 0
                        );
                        continue 2;
                    }
                    $res_spec = $spec_model -> where(array('sku'=>$v['Sku'])) -> find();
                    if($res_spec){
                        $spec_array = array(
                            'goods_id' => $res['goods_id'],
                            'sku' => $v['Sku'],
                            'price' => $v['Price'],
                            'stock' => $v['StockNum'],
//                            'spec_1' => $_POST['ProductItems'][$key]['ProductImgs'][$k] ? $_POST['ProductItems'][$key]['ProductImgs'][$k] : '',
                            'spec_1value' => $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][0]['c'] ? $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][0]['c'] : '',

                            //临时图 需要改
                            //临时图 需要改
                            'spec_2' => $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][0]['v'] ? $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][0]['v'] : '',
                            'spec_3' => $res_stock['stock_name'],
                            'spec_3value' => $value['VendorId'].$v['CustomsChannelId'],
                            'spec_4' => $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][1]['v'] ? $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][1]['v'] : '',
                            'tax_price' => round($consolidated_tax * $v['Price'],2),
                            'barcode' => $v['Gtin'],

                        );
                        $res_spec = $spec_model ->where(array('spec_id'=>$res_spec['spec_id']))->save($spec_array);

                        if($res_spec === false){
                            $send_array[] = array(
                                'Sku' => $value['Sku'],
                                'Field' => '',
                                'Msg' => '规格修改失败',
                                "Result" => 0
                            );
                            continue 2;
                        }

                    }else{
                        $spec_array = array(
                            'goods_id' => $res['goods_id'],
                            'sku' => $v['Sku'],
                            'price' => $v['Price'],
                            'stock' => $v['StockNum'],
//                            'spec_1' => $_POST['ProductItems'][$key]['ProductImgs'][$k] ? $_POST['ProductItems'][$key]['ProductImgs'][$k] : '',
                            //临时图 需要改
                            //临时图 需要改
                            'spec_1value' => $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][0]['v'] ? $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][0]['v'] : '',

                            'spec_2' => $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][1]['v'] ? $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][1]['v'] : '',
                            'spec_3' => $res_stock['stock_name'],
                            'spec_3value' => $value['VendorId'].$v['CustomsChannelId'],
                            'spec_4' => $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][2]['v'] ? $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][2]['v'] : '',
                            'tax_price' => round($consolidated_tax * $v['Price'],2),
                            'barcode' => $v['Gtin'],
                        );
                        $res_spec = $spec_model->add($spec_array);
                        if(!$res_spec){
                            $send_array[] = array(
                                'Sku' => $value['Sku'],
                                'Field' => '',
                                'Msg' => '规格修改失败',
                                "Result" => 0
                            );
                            continue 2;
                        }
                    }
                }

                //查询原默认规格是否存在
                $res_default = M('goods_spec')->where(array('spec_id'=>$res['default_spec']))->find();
                //如果不存在查找一条
                if(!$res_default){
                    $res_newdefault = M('goods_spec')->where(array('goods_id'=>$res['goods_id']))->find();
                    if(!$res_newdefault){
                        $send_array[] = array(
                            'Sku' => $value['Sku'],
                            'Field' => '',
                            'Msg' => '原规格查询失败',
                            "Result" => 0
                        );
                        continue;
                    }
                    $spec_id = $res_newdefault['spec_id'];
                }else{
                    $spec_id = $res_default['spec_id'];
                }
                $goods_array = array(
                    'sku' => $value['Sku'],
                    'goods_name' => $value['Name'],
                    'description' => '<p>'.$value['ShortDescription'].'</p>',
                    'store_id' => $value['VendorId'],
                    'price' => $value['Price'],
                    'quantity' => $value['StockQuantity'],
                    'market_price' => $value['OldPrice'],
                    'brand' => $temp_logo,
                    'if_show' => $value['Published'],
                    'add_time' => $value['CreatedTimeStamp'],
                    'last_update' => $value['UpdateTimeStamp'],
                    //临时图 需要改
//                    'default_image' => $value['DefaultImg'],
                    'country_id' => $temp_country['id'],
                    'unit_id' => $temp_unit['id'],
                    'wrap_id' => $temp_wrap['id'],
                    'tax_id' => $tax_id,
                    'spec_qty' => $value['SpecCount'] ? $value['SpecCount'] : 1,
                    'default_spec' => $spec_id,
                    'spec_name_1' => $value['SpecCount'] ? '颜色' : '',
                    'spec_name_2' => $value['SpecCount'] && $_POST['ProductItems'][$key]['SpecItems'][0]['AttrComb'][0] ? $_POST['ProductItems'][$key]['SpecItems'][0]['AttrComb'][0]['k'] : '',
                    'spec_name_3' => '发货方式',
                    'spec_name_4' => $value['SpecCount'] && $_POST['ProductItems'][$key]['SpecItems'][0]['AttrComb'][1] ? $_POST['ProductItems'][$key]['SpecItems'][0]['AttrComb'][1]['k'] : ''
                );

                $res_goods = M('goods')->where(array('goods_id'=>$res['goods_id']))->save($goods_array);

                if($res_goods === false){
                    $send_array[] = array(
                        'Sku' => $value['Sku'],
                        'Field' => '',
                        'Msg' => '规格修改失败',
                        "Result" => 0
                    );
                    continue;
                }
                $send_array[] = array(
                    'Sku' => $value['Sku'],
                    'Field' => '',
                    'Msg' => '修改商品成功',
                    "Result" => 1
                );


            //收到的数据无规格
            }else{
                //查询原来是否有规格
                //有
                if($res['spec_qty'] > 0){
                    //删除除了主规格的规格
                    $temp['spec_id'] = array('not in',$res['default_spec']);
                    $temp['goods_id'] = $res['goods_id'];
                    $res_remove = M('goods_spec')->where($temp)->delete();
                    if($res_remove === false){
                        $send_array[] = array(
                            'Sku' => $value['Sku'],
                            'Field' => '',
                            'Msg' => '规格删除失败',
                            "Result" => 0
                        );
                        continue;
                    }
                    //修改默认规格的属性
                //无
                }else{
                }
                //查询原默认规格是否存在
                $res_default = M('goods_spec')->where(array('spec_id'=>$res['default_spec']))->find();
                //如果不存在查找一条
                if(!$res_default){
                    $res_newdefault = M('goods_spec')->where(array('goods_id'=>$res['goods_id']))->find();
                    if(!$res_newdefault){
                        $send_array[] = array(
                            'Sku' => $value['Sku'],
                            'Field' => '',
                            'Msg' => '原规格查询失败',
                            "Result" => 0
                        );
                        continue;
                    }
                    $spec_id = $res_newdefault['spec_id'];
                }else{
                    $spec_id = $res_default['spec_id'];
                }
                $goods_array = array(
                    'sku' => $value['Sku'],
                    'goods_name' => $value['Name'],
                    'description' => '<p>'.$value['ShortDescription'].'</p>',
                    'store_id' => $value['VendorId'],
                    'price' => $value['Price'],
                    'quantity' => $value['StockQuantity'],
                    'market_price' => $value['OldPrice'],
                    'brand' => $temp_logo,
                    'if_show' => $value['Published'],
                    'add_time' => $value['CreatedTimeStamp'],
                    'last_update' => $value['UpdateTimeStamp'],
                    //临时图 需要改
//                    'default_image' => $value['DefaultImg'],
                    'country_id' => $temp_country['id'],
                    'unit_id' => $temp_unit['id'],
                    'wrap_id' => $temp_wrap['id'],
                    'tax_id' => $tax_id,
                    'spec_qty' => 0,
                    'default_spec' => $spec_id,
                    'spec_name_1' => $value['SpecCount'] ? '颜色' : '',
                    'spec_name_2' => $value['SpecCount'] && $_POST['ProductItems'][$key]['SpecItems'][0]['AttrComb'][0] ? $_POST['ProductItems'][$key]['SpecItems'][0]['AttrComb'][0]['k'] : '',
                    'spec_name_3' => '发货方式',
                    'spec_name_4' => $value['SpecCount'] && $_POST['ProductItems'][$key]['SpecItems'][0]['AttrComb'][1] ? $_POST['ProductItems'][$key]['SpecItems'][0]['AttrComb'][1]['k'] : ''
                );

                $res_goods = M('goods')->where(array('goods_id'=>$res['goods_id']))->save($goods_array);

                if($res_goods === false){
                    $send_array[] = array(
                        'Sku' => $value['Sku'],
                        'Field' => '',
                        'Msg' => '规格修改失败',
                        "Result" => 0
                    );
                    continue;
                }


                $send_array[] = array(
                    'Sku' => $value['Sku'],
                    'Field' => '',
                    'Msg' => '修改商品成功',
                    "Result" => 1
                );

            }
        }

        $return_array = array(
            'Success' => 1,
            'Code' => 200,
            'Msg' => '商品状态修改成功',
            "Result" => 0
        );
        echo json_encode($return_array,JSON_UNESCAPED_UNICODE);
        exit;
    }

    public function addGoods(){
//        $rs = '{
//	"Id": 0,
//	"ProductItems": [{
//		"Name": "EA7 女士短袖T恤衫",
//		"ShortDescription": null,
//		"VendorId": 2,
//		"Sku": "3ZTT83",
//		"Price": 600.0000,
//		"StockQuantity": 10000.0,
//		"OldPrice": 600.0000,
//		"SpecCount": 3,
//		"Manufacturer": "EA7",
//		"Published": 1,
//		"CreatedOnUtc": "2019-06-28T03:14:00.49",
//		"UpdateOnUtc": "2019-06-28T03:14:00.49",
//		"CreatedTimeStamp": 1561662840,
//		"UpdateTimeStamp": 1561662840,
//		"DefaultImg": "http://xinqing19830730.xicp.vip:58769/content/images/thumbs/0000160_ea7-t.jpeg",
//		"SortNum": 0,
//		"HsCode": "6109100022",
//		"CountryId": 434,
//		"CountryName": "秘鲁",
//		"UnitId": "011",
//		"UnitName": "件",
//		"WrapId": "5H4",
//		"WrapName": "塑料薄膜袋",
//		"VATRate": 0.0900,
//		"ConsumptionTaxRate": 0.0000,
//		"TradeType": 2,
//		"CustomsChannelId": "35",
//		"UploadType": 0,
//		"UploadStatus": 0,
//		"ProductImgs": "[{\"order\":1,\"url\":\"http://xinqing19830730.xicp.vip:58769/content/images/thumbs/0000160_ea7-t.jpeg\"},{\"order\":2,\"url\":\"http://xinqing19830730.xicp.vip:58769/content/images/thumbs/0000161_ea7-t.jpeg\"},{\"order\":3,\"url\":\"http://xinqing19830730.xicp.vip:58769/content/images/thumbs/0000162_ea7-t.jpeg\"}]",
//		"SpecItems": [{
//			"ProductId": 105,
//			"Sku": "3ZTT83 TJ12Z 1200-S",
//			"StockNum": 10000,
//			"CreatTime": "2019-06-28T03:14:00.49",
//			"UpdateTime": null,
//			"CustomsChannelId": 35,
//			"HsCode": "6109100022",
//			"CountryId": 434,
//			"CountryName": "秘鲁",
//			"UnitId": "011",
//			"UnitName": "件",
//			"WrapId": "5H4",
//			"WrapName": "塑料薄膜袋",
//			"VATRate": 0.0900,
//			"ConsumptionTaxRate": 0.0000,
//			"TradeType": 2,
//			"Published": 0,
//			"AttrComb": "[{\"k\":\"颜色\",\"v\":\"黑色\"},{\"k\":\"尺码\",\"v\":\"S\"}]",
//			"Gtin": "805959691307410612000009",
//			"Price": 0.0100,
//			"CiqCountry": 604,
//			"InternationalCode": "3ZTT83 TJ12Z 1200"
//		}, {
//			"ProductId": 105,
//			"Sku": "3ZTT83 TJ12Z 1442-L",
//			"StockNum": 10000,
//			"CreatTime": "2019-06-28T03:14:00.49",
//			"UpdateTime": null,
//			"CustomsChannelId": 35,
//			"HsCode": "6109100022",
//			"CountryId": 434,
//			"CountryName": "秘鲁",
//			"UnitId": "011",
//			"UnitName": "件",
//			"WrapId": "5H4",
//			"WrapName": "塑料薄膜袋",
//			"VATRate": 0.0900,
//			"ConsumptionTaxRate": 0.0000,
//			"TradeType": 2,
//			"Published": 0,
//			"AttrComb": "[{\"k\":\"颜色\",\"v\":\"红色\"},{\"k\":\"尺码\",\"v\":\"L\"}]",
//			"Gtin": "805959691312810612000009",
//			"Price": 0.0100,
//			"CiqCountry": 604,
//			"InternationalCode": "3ZTT83 TJ12Z 1442"
//		}, {
//			"ProductId": 105,
//			"Sku": "3ZTT83 TJ12Z 3905-M",
//			"StockNum": 10000,
//			"CreatTime": "2019-06-28T03:14:00.49",
//			"UpdateTime": null,
//			"CustomsChannelId": 35,
//			"HsCode": "6109100022",
//			"CountryId": 434,
//			"CountryName": "秘鲁",
//			"UnitId": "011",
//			"UnitName": "件",
//			"WrapId": "5H4",
//			"WrapName": "塑料薄膜袋",
//			"VATRate": 0.0900,
//			"ConsumptionTaxRate": 0.0000,
//			"TradeType": 2,
//			"Published": 0,
//			"AttrComb": "[{\"k\":\"颜色\",\"v\":\"灰色\"},{\"k\":\"尺码\",\"v\":\"M\"}]",
//			"Gtin": "805959691327210612000004",
//			"Price": 0.0100,
//			"CiqCountry": 604,
//			"InternationalCode": "3ZTT83 TJ12Z 3905"
//		}],
//		"Gtin": null,
//		"CiqCountry": 604,
//		"InternationalCode": "3ZTT83",
//		"OutCode": null,
//		"ErrorMessage": null
//	}],
//	"ClientGuid": null,
//	"ClientName": null
//}';
        $GLOBALS['HTTP_RAW_POST_DATA'] = stripslashes($GLOBALS['HTTP_RAW_POST_DATA']);
        $GLOBALS['HTTP_RAW_POST_DATA'] = str_replace('"[','[',$GLOBALS['HTTP_RAW_POST_DATA']);
        $GLOBALS['HTTP_RAW_POST_DATA'] = str_replace(']"',']',$GLOBALS['HTTP_RAW_POST_DATA']);
//        $rs = stripslashes($rs);
//        $rs = str_replace('"[','[',$rs);
//        $rs = str_replace(']"',']',$rs);
//        $_POST = json_decode($rs,true);
        $_POST = json_decode($GLOBALS['HTTP_RAW_POST_DATA'],true);

//        var_dump($GLOBALS['HTTP_RAW_POST_DATA']);exit;
        if(!$_POST || !is_array($_POST)){
            $return_array = array(
                'MessageCode' => 2,
                'Message' => '参数错误'
            );
            echo json_encode($return_array,JSON_UNESCAPED_UNICODE);
            exit;
        }

        $goods_model = M('goods');
        $spec_model = M('goods_spec');
        $brand_model = M('brand');
        $country_model = M('country_info');
        $unit_model = M('unit');
        $wrap_model = M('wrap');
        $tax_model = M('my_tax');
        $stock_model = M('storestock');
        $store_model = M('store');

        if(!$_POST['ProductItems'] || !is_array($_POST['ProductItems'])){
            $return_array = array(
                'Sku' => '',
                'Field' => 'Manufacturer',
                'Msg' => '参数错误',
                "Result" => 0
            );
            echo json_encode($return_array,JSON_UNESCAPED_UNICODE);
            exit;
        }
        $send_array = array();
        $pic_array = array();

        foreach ($_POST['ProductItems'] as $key => $value){
            if($value['SpecItems'] && is_array($value['SpecItems'])){
                //logo
                $temp_logo = trim($value['Manufacturer']);
                if($temp_logo){
                    $res_logo = $brand_model -> where(array('brand_name'=>$temp_logo)) -> find();
                    if(!$res_logo){
                        $logo_add = $brand_model -> add(array('brand_name'=>$temp_logo));
                        if(!$logo_add){
                            $send_array[] = array(
                                'Sku' => $value['Sku'],
                                'Field' => 'Manufacturer',
                                'Msg' => '品牌添加失败',
                                "Result" => 0
                            );
                            continue;
                        }
                    }
                }

                //出产地
                $temp_country = $country_model -> where(array('country_code'=>$value['CountryId'])) ->find();
                if(!$temp_country){
                    $send_array[] = array(
                        'Sku' => $value['Sku'],
                        'Field' => 'CountryId',
                        'Msg' => '出产地查询失败',
                        "Result" => 0
                    );
                    continue;
                }
                //单位
                $temp_unit = $unit_model -> where(array('unit_code'=>$value['UnitId'])) ->find();
                if(!$temp_unit){
                    $send_array[] = array(
                        'Sku' => $value['Sku'],
                        'Field' => 'CountryId',
                        'Msg' => '出产地查询失败',
                        "Result" => 0
                    );
                    continue;
                }

                //包装

                $temp_wrap = $wrap_model -> where(array('wrap_code'=>$value['WrapId'])) ->find();

                if(!$temp_wrap){
                    $send_array[] = array(
                        'Sku' => $value['Sku'],
                        'Field' => 'WrapId',
                        'Msg' => '包装查询失败',
                        "Result" => 0
                    );
                    continue;
                }

                //税率
                $consolidated_tax = get_consolidated_tax($value['ConsumptionTaxRate'],$value['VATRate']);
                $r['add_tax'] = $value['VATRate'];
                $r['consumption_tax'] = $value['ConsumptionTaxRate'];
                $temp_tax = $tax_model -> where(array('consumption_tax'=>$r)) ->find();

                if(!$temp_tax){
                    $rx['add_tax'] = $value['VATRate'];
                    $rx['consumption_tax'] = $value['ConsumptionTaxRate'];
                    $rx['consolidated_tax'] = $value['consolidated_tax'];
                    $rx['tax_name'] = '消费税为'.$value['ConsumptionTaxRate'].'的商品';
                    $rx['consolidated_tax'] = $consolidated_tax;
                    $add_tax = $tax_model -> add($rx);
                    if(!$add_tax){
                        $send_array[] = array(
                            'Sku' => $value['Sku'],
                            'Field' => 'ConsumptionTaxRate',
                            'Msg' => '税率查询失败',
                            "Result" => 0
                        );
                        continue;
                    }
                    $tax_id = $add_tax;
                }else{
                    $tax_id = $temp_tax['tax_id'];
                    $consolidated_tax = $temp_tax['consolidated_tax'];
                }
                //店铺
                $resStore = $store_model -> where(array('store_id'=>$value['VendorId'])) -> find();
                if(!$resStore){
                    $send_array[] = array(
                        'Sku' => $value['Sku'],
                        'Field' => 'VendorId',
                        'Msg' => '店铺查询失败',
                        "Result" => 0
                    );
                    continue;
                }


                $pic = arraySort($_POST['ProductImgs'][$key]['SpecItems'], 'order', SORT_ASC);
                $goods_array = array(
                    'sku' => $value['Sku'],
                    'goods_name' => $value['Name'],
                    'description' => '<p>'.$value['ShortDescription'].'</p>',
                    'store_id' => $value['VendorId'],
                    'price' => $value['Price'],
                    'quantity' => $value['StockQuantity'],
                    'market_price' => $value['OldPrice'],
                    'brand' => $temp_logo,
                    'if_show' => $value['Published'],
                    'add_time' => $value['CreatedTimeStamp'],
                    'last_update' => $value['UpdateTimeStamp'],
                    //临时图 需要改
                    'default_image' => $value['DefaultImg'],
                    'country_id' => $temp_country['id'],
                    'unit_id' => $temp_unit['id'],
                    'wrap_id' => $temp_wrap['id'],
                    'tax_id' => $tax_id,
                    'spec_qty' => $value['SpecCount'] ? $value['SpecCount'] : 1,
                    'spec_name_1' => $value['SpecCount'] && $_POST['ProductItems'][$key]['SpecItems'][0]['AttrComb'][0] ? $_POST['ProductItems'][$key]['SpecItems'][0]['AttrComb'][0]['k'] : '',
                    'spec_name_2' => $value['SpecCount'] && $_POST['ProductItems'][$key]['SpecItems'][0]['AttrComb'][1] ? $_POST['ProductItems'][$key]['SpecItems'][0]['AttrComb'][1]['k'] : '',
                    'spec_name_3' => '发货方式',
                    'spec_name_4' => $value['SpecCount'] && $_POST['ProductItems'][$key]['SpecItems'][0]['AttrComb'][2] ? $_POST['ProductItems'][$key]['SpecItems'][0]['AttrComb'][2]['k'] : ''
                );

                $res_goods = $goods_model -> add($goods_array);


                if(!$res_goods){
                    $send_array[] = array(
                        'Sku' => $value['Sku'],
                        'Field' => '',
                        'Msg' => '添加商品失败',
                        "Result" => 0
                    );
                    continue;
                }
                $pics_array = array();
                $first_id = '';

                foreach ($_POST['ProductItems'][$key]['SpecItems'] as $k => $v){

                    //仓库
                    $res_stock = $stock_model -> where(array('storestock_id'=>$value['VendorId'].$v['CustomsChannelId'])) -> find();

                    if(!$res_stock){
                        $send_array[] = array(
                            'Sku' => $value['Sku'],
                            'Field' => 'CustomsChannelId',
                            'Msg' => '查询报关通道失败',
                            "Result" => 0
                        );
                        continue 2;
                    }

                    //barcode
                    if(!$v['Gtin']){
                        $send_array[] = array(
                            'Sku' => $value['Sku'],
                            'Field' => 'Barcode',
                            'Msg' => 'Barcode不能为空',
                            "Result" => 0
                        );
                        continue 2;
                    }
                    $spec_array = array(
                        'goods_id' => $res_goods,
                        'sku' => $v['Sku'],
                        'price' => $v['Price'],
                        'stock' => $v['StockNum'],
                        'spec_1' => $_POST['ProductItems'][$key]['ProductImgs'][$k] ? $_POST['ProductItems'][$key]['ProductImgs'][$k] : '',
                        'spec_1value' => $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][0]['v'] ? $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][0]['v'] : '',
                        //临时图 需要改
                        //临时图 需要改
                        'spec_2' => $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][1]['v'] ? $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][1]['v'] : '',
                        'spec_3' => $res_stock['stock_name'],
                        'spec_3value' => $value['VendorId'].$v['CustomsChannelId'],
                        'spec_4' => $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][2]['v'] ? $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][2]['v'] : '',
                        'tax_price' => round($consolidated_tax * $v['Price'],2),
                        'barcode' => $v['Gtin'],

                    );
                    $res_spec = $spec_model -> add($spec_array);

                    if($k == 0){
                        $first_id = $res_spec;
                    }
                    if(!$res_spec){
                        $send_array[] = array(
                            'Sku' => $value['Sku'],
                            'Field' => '',
                            'Msg' => '添加规格失败',
                            "Result" => 0
                        );
                        continue 2;
                    }

                    $pics_array[] = array(
                        'spec_id' => $res_spec,
                        'url' => $_POST['ProductItems'][$key]['ProductImgs'][$k]['url']
                    );

                }
                $pic_array[] = array(
                    'goods_id'=> $res_goods,
                    'store_id'=> $value['VendorId'],
                    'url' => $value['DefaultImg'],
                    'spec' =>  $pics_array
                );
//                sync_data('http://customs.jingjing.shop/api/ecmalltest',json_encode($pic_array));

                //将第一个spec_id插入进goods表

                $res = $goods_model -> where(array('goods_id'=>$res_goods))->save(array('default_spec'=>$first_id));

                if(!$res){
                    $send_array[] = array(
                        'Sku' => $value['Sku'],
                        'Field' => '',
                        'Msg' => '添加商品规格id失败',
                        "Result" => 0
                    );
                    continue;
                }else{
                    $send_array[] = array(
                        'Sku' => $value['Sku'],
                        'Field' => '',
                        'Msg' => '添加商品成功',
                        "Result" => 1
                    );
                }
                $res_statistics = M('goods_statistics')->add(array('goods_id'=>$res_goods));
                if(!$res_statistics){
                    $send_array[] = array(
                        'Sku' => $value['Sku'],
                        'Field' => '',
                        'Msg' => '添加商品收藏表失败',
                        "Result" => 0
                    );
                    continue;
                }
                $file = fopen("test.txt","w+");
                fwrite($file,json_encode($pic_array,true));
                fclose($file);
                $this->download($pic_array);


            }else{
                //logo
                $temp_logo = trim($value['Manufacturer']);
                if($temp_logo){
                    $res_logo = $brand_model -> where(array('brand_name'=>$temp_logo)) -> find();
                    if(!$res_logo){
                        $logo_add = $brand_model -> add(array('brand_name'=>$temp_logo));
                        if(!$logo_add){
                            $send_array[] = array(
                                'Sku' => $value['Sku'],
                                'Field' => 'Manufacturer',
                                'Msg' => '品牌添加失败',
                                "Result" => 0
                            );
                            continue;
                        }
                    }
                }

                //出产地
                $temp_country = $country_model -> where(array('country_code'=>$value['CountryId'])) ->find();
                if(!$temp_country){
                    $send_array[] = array(
                        'Sku' => $value['Sku'],
                        'Field' => 'CountryId',
                        'Msg' => '出产地查询失败',
                        "Result" => 0
                    );
                    continue;
                }
                //单位
                $temp_unit = $unit_model -> where(array('unit_code'=>$value['UnitId'])) ->find();
                if(!$temp_unit){
                    $send_array[] = array(
                        'Sku' => $value['Sku'],
                        'Field' => 'CountryId',
                        'Msg' => '出产地查询失败',
                        "Result" => 0
                    );
                    continue;
                }

                //包装

                $temp_wrap = $wrap_model -> where(array('wrap_code'=>$value['WrapId'])) ->find();

                if(!$temp_wrap){
                    $send_array[] = array(
                        'Sku' => $value['Sku'],
                        'Field' => 'WrapId',
                        'Msg' => '包装查询失败',
                        "Result" => 0
                    );
                    continue;
                }

                //税率
                $consolidated_tax = get_consolidated_tax($value['ConsumptionTaxRate'],$value['VATRate']);
                $r['add_tax'] = $value['VATRate'];
                $r['consumption_tax'] = $value['ConsumptionTaxRate'];
                $temp_tax = $tax_model -> where($r) ->find();

                if(!$temp_tax){
                    $rx['add_tax'] = $value['VATRate'];
                    $rx['consumption_tax'] = $value['ConsumptionTaxRate'];
                    $rx['consolidated_tax'] = $value['consolidated_tax'];
                    $rx['tax_name'] = '消费税为'.$value['ConsumptionTaxRate'].'的商品';
                    $rx['consolidated_tax'] = $consolidated_tax;
                    $add_tax = $tax_model -> add($rx);
                    if(!$add_tax){
                        $send_array[] = array(
                            'Sku' => $value['Sku'],
                            'Field' => 'ConsumptionTaxRate',
                            'Msg' => '税率查询失败',
                            "Result" => 0
                        );
                        continue;
                    }
                    $tax_id = $add_tax;
                }else{
                    $tax_id = $temp_tax['tax_id'];
                    $consolidated_tax = $temp_tax['consolidated_tax'];
                }
                //店铺
                $resStore = $store_model -> where(array('store_id'=>$value['VendorId'])) -> find();
                if(!$resStore){
                    $send_array[] = array(
                        'Sku' => $value['Sku'],
                        'Field' => 'VendorId',
                        'Msg' => '店铺查询失败',
                        "Result" => 0
                    );
                    continue;
                }
                $_POST['ProductImgs'][$key]['SpecItems'] = arraySort($_POST['ProductImgs'][$key]['SpecItems'], 'order', SORT_DESC);
                $goods_array = array(
                    'sku' => $value['Sku'],
                    'goods_name' => $value['Name'],
                    'description' => '<p>'.$value['ShortDescription'].'</p>',
                    'store_id' => $value['VendorId'],
                    'price' => $value['Price'],
                    'quantity' => $value['StockQuantity'],
                    'market_price' => $value['OldPrice'],
                    'brand' => $temp_logo,
                    'if_show' => $value['Published'],
                    'add_time' => $value['CreatedTimeStamp'],
                    'last_update' => $value['UpdateTimeStamp'],
                    //临时图 需要改
                    'default_image' => $value['DefaultImg'],
                    'country_id' => $temp_country['id'],
                    'unit_id' => $temp_unit['id'],
                    'wrap_id' => $temp_wrap['id'],
                    'tax_id' => $tax_id,
                    'spec_qty' => 0,
                    'spec_name_1' => $value['SpecCount'] && $_POST['ProductItems'][$key]['SpecItems'][0]['AttrComb'][0] ? $_POST['ProductItems'][$key]['SpecItems'][0]['AttrComb'][0]['k'] : '',
                    'spec_name_2' => $value['SpecCount'] && $_POST['ProductItems'][$key]['SpecItems'][0]['AttrComb'][1] ? $_POST['ProductItems'][$key]['SpecItems'][0]['AttrComb'][1]['k'] : '',
                    'spec_name_3' => '发货方式',
                    'spec_name_4' => $value['SpecCount'] && $_POST['ProductItems'][$key]['SpecItems'][0]['AttrComb'][2] ? $_POST['ProductItems'][$key]['SpecItems'][0]['AttrComb'][2]['k'] : '',
                    'barcode' => $value['Gtin'],
                );
                $res_goods = $goods_model -> add($goods_array);
                if(!$res_goods){
                    $send_array[] = array(
                        'Sku' => $value['Sku'],
                        'Field' => '',
                        'Msg' => '添加商品失败',
                        "Result" => 0
                    );
                    continue;
                }
                $res_statistics = M('goods_statistics')->add(array('goods_id'=>$res_goods));
                if(!$res_statistics){
                    $send_array[] = array(
                        'Sku' => $value['Sku'],
                        'Field' => '',
                        'Msg' => '添加商品收藏表失败',
                        "Result" => 0
                    );
                    continue;
                }
//                foreach ($_POST['ProductItems'][$key]['SpecItems'] as $k => $v){
                    //仓库
                    $res_stock = $stock_model -> where(array('storestock_id'=>$value['VendorId'].$value['CustomsChannelId'])) -> find();
                    if(!$res_stock){
                        $send_array[] = array(
                            'Sku' => $value['Sku'],
                            'Field' => 'CustomsChannelId',
                            'Msg' => '查询报关通道失败',
                            "Result" => 0
                        );
                        continue;
                    }
                //barcode
                if(!$value['Gtin']){
                    $send_array[] = array(
                        'Sku' => $value['Sku'],
                        'Field' => 'Barcode',
                        'Msg' => 'Barcode不能为空',
                        "Result" => 0
                    );
                    continue;
                }
                    $spec_array = array(
                        'goods_id' => $res_goods,
                        'sku' => $value['Sku'],
                        'price' => $value['Price'],
                        'stock' => 0,
                        //临时图 需要改
                        'spec_3' => $res_stock['stock_name'],
                        'spec_3value' => $value['VendorId'].$value['CustomsChannelId'],
                        'tax_price' => round($consolidated_tax * $value['Price'],2),
                    );

//                }
                $res_spec = $spec_model -> add($spec_array);
                if(!$res_spec){
                    $send_array[] = array(
                        'Sku' => $value['Sku'],
                        'Field' => '',
                        'Msg' => '添加规格失败',
                        "Result" => 0
                    );
                    continue;
                }
                //将第一个spec_id插入进goods表

                $res = $goods_model -> where(array('goods_id'=>$res_goods))->save(array('default_spec'=>$res_spec));

                if(!$res){
                    $send_array[] = array(
                        'Sku' => $value['Sku'],
                        'Field' => '',
                        'Msg' => '添加商品规格id失败',
                        "Result" => 0
                    );
                    continue;
                }else{
                    $send_array[] = array(
                        'Sku' => $value['Sku'],
                        'Field' => '',
                        'Msg' => '添加商品成功',
                        "Result" => 1
                    );
                }
            }

        }
//        $url = C('ERP_URL'); #url 地址必须 http://xxxxx
//        $port = C('ERP_URL');
//        $t=1;
//        $res = _post_to_oms($url,$port,$t,'post',$send_array);
        if(count($send_array) > 0){
            echo json_encode($send_array,JSON_UNESCAPED_UNICODE);
            exit;
        }
        $return_array = array(
            'Success' => 1,
            'Code' => 200,
            'Msg' => '商品状态修改成功',
            "Result" => 0
        );
        echo json_encode($return_array,JSON_UNESCAPED_UNICODE);
        exit;

    }

    public function object_array($array) {
        if(is_object($array)) {
            $array = (array)$array;
        } if(is_array($array)) {
            foreach($array as $key=>$value) {
                $array[$key] = object_array($value);
            }
        }
        return $array;
    }



//    public function download()
    public function download($data)
    {


        $send_data = array();
//        $data = array(
//            0 => array(
//                'goods_id'=> 109,
//                'store_id'=> 2,
//                'url' => 'http://pic3.nipic.com/20090514/2639204_233912087_2.jpg',
//                'spec' => array(
//                    0 =>array(
//                        'spec_id' => '127',
//                        'url' => 'http://pic1a.nipic.com/2008-10-22/20081022103550586_2.jpg'
//                    ),
//                    1 =>array(
//                        'spec_id' => '128',
//                        'url' => 'http://pic1a.nipic.com/2008-10-22/20081022103550586_2.jpg'
//                    ),
//                    2 =>array(
//                        'spec_id' => '129',
//                        'url' => 'http://pic1a.nipic.com/2008-10-22/20081022103550586_2.jpg'
//                    ),
//                    3 =>array(
//                        'spec_id' => '130',
//                        'url' => 'http://pic1a.nipic.com/2008-10-22/20081022103550586_2.jpg'
//                    ),
//                    4 =>array(
//                        'spec_id' => '131',
//                        'url' => 'http://pic1a.nipic.com/2008-10-22/20081022103550586_2.jpg'
//                    )
//
//                )
//            )
//        );

//        $images = array( 'http://pic3.nipic.com/20090514/2639204_233912087_2.jpg',
//            'http://pic1a.nipic.com/2008-10-22/20081022103550586_2.jpg');
        foreach ( $data as $k => $v ) {

            if(strpos(__ROOT__,'ecmall')){
                $path = $_SERVER['DOCUMENT_ROOT'].'/ecmall/data/files/store_'.$v['store_id'].'/goods_'.$v['goods_id'].'/';
            }else{
                $path = $_SERVER['DOCUMENT_ROOT'].'/data/files/store_'.$v['store_id'].'/goods_'.$v['goods_id'].'/';
            }

            $file_name = downloadImage($v['url'],$path,1);

            $thumb_path = './../data/files/store_'.$v['store_id'].'/goods_'.$v['goods_id'].'/'.$file_name;

            $save_path = './../data/files/store_'.$v['store_id'].'/goods_'.$v['goods_id'].'/small_'.$file_name;


            make_thumb($thumb_path,$save_path);

            //取data后面

            $path_arr = explode('data',$path);
//            $path_str = 'data'.$path_arr[1];
            $path_str = 'data'.$path_arr[2];

            $thumb_arr = explode('data',$save_path);
//            $thumb_str = 'data'.$thumb_arr[1];
            $thumb_str = 'data'.$thumb_arr[2];

            $send_data[$k]['goods_id'] = $v['goods_id'];
            $send_data[$k]['store_id'] = $v['store_id'];
            $send_data[$k]['file_name'] = $file_name;
            $send_data[$k]['file_path'] = $path_str.$file_name;
            $send_data[$k]['thumb_name'] = 'small_'.$file_name;
            $send_data[$k]['thumb_path'] = $thumb_str.$file_name;
            $send_data[$k]['spec'] = array();
            foreach ($data[$k]['spec'] as $key => $value){
                if(strpos(__ROOT__,'ecmall')){
                    $path = $_SERVER['DOCUMENT_ROOT'].'/ecmall/data/files/store_'.$v['store_id'].'/goodsspec/';
                }else{
                    $path = $_SERVER['DOCUMENT_ROOT'].'/data/files/store_'.$v['store_id'].'/goodsspec/';
                }
                $file_spec_name = downloadImage($value['url'],$path,2);


                //取data后面

                $path_arr = explode('data',$path);
//                $path_str = 'data'.$path_arr[1];
                $path_str = 'data'.$path_arr[2];

                $send_data[$k]['spec'][$key] = array();
                $send_data[$k]['spec'][$key]['spec_id'] = $value['spec_id'];
                $send_data[$k]['spec'][$key]['file_name'] = $file_spec_name;
                $send_data[$k]['spec'][$key]['file_path'] = $path_str.$file_spec_name;
            }
        }
        save_sql($send_data);
    }

}

/**
 * 二维数组根据某个字段排序
 * @param array $array 要排序的数组
 * @param string $keys   要排序的键字段
 * @param string $sort  排序类型  SORT_ASC     SORT_DESC
 * @return array 排序后的数组
 */
function arraySort($array, $keys, $sort = SORT_DESC) {
    $keysValue = array();
    foreach ($array as $k => $v) {
        $keysValue[$k] = $v[$keys];
    }
    array_multisort($keysValue, $sort, $array);
    return $array;
}
function random_filename()
{
    $seedstr = explode(" ", microtime(), 5);
    $seed    = $seedstr[0] * 10000;
    srand($seed);
    $random  = rand(1000,10000);

    return date("YmdHis", time()) . $random;
}


//计算综合税
function get_consolidated_tax($consumption_tax = 0,$add_tax = 0.13){
    return round((($consumption_tax + $add_tax) / (1 - $consumption_tax)) * 0.7,3);
}

//下载远程图片

function downloadImage($url,$path,$type)
{
    $ch = curl_init(); //curl_init(): 初始化一个新的会话，返回一个cURL句柄，供curl_setopt(), curl_exec()和curl_close() 函数使用。

    curl_setopt($ch, CURLOPT_URL, $url);//curl_setopt(): 设置一个cURL传输选项,

//CURLOPT_URL: 需要获取的 URL 地址，也可以在curl_init() 初始化会话的时候。

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //CURLOPT_RETURNTRANSFER: TRUE将curl_exec()获取的信息以字符串返回，而不是直接输出。

    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);//CURLOPT_CONNECTTIMEOUT: 在尝试连接时等待的秒数。设置为0，则无限等待。

    $file = curl_exec($ch);//curl_exec(): 执行一个cURL会话

    curl_close($ch);//curl_close(): 关闭一个cURL会话



    $rs = mkdirs_1($path);

    $res = saveAsImage($url, $file, $path, $type);
    return $res;
}

//type
// 1:商品主图

// 2:商品规格图

function saveAsImage($url, $file, $path ,$type = 1)
{


    $filenames = pathinfo($url, PATHINFO_BASENAME);//pathinfo(): 返回文件路径的信息

    $str=explode('.',$filenames);

    if($type == 1){
        $filename = date("YmdHis".(time() % 200))+rand(100000,999999).'.'.$str[1];
    }else if($type == 2){
//        $filename = 'spec_'.date("YmdHis".(time() % 200)).'.'.$str[1];
        $filename = date("YmdHis".(time() % 200))+rand(100000,999999).'.'.$str[1];

    }


    $resource = fopen($path.$filename, 'a');//fopen(): 打开文件或url

    $rs = fwrite($resource, $file);//fwrite(): 写入文件

//    $ming = date("YmdHis".(time() % 200));

    fclose($resource);//fclose(): 关闭一个已经打开的文件指针
    if($type == 2){
        $filename1 = 'spec_'.date("YmdHis".(time() % 200)).'.'.$str[1];
        $resource = fopen($path.$filename1, 'a');//fopen(): 打开文件或url

        $rs = fwrite($resource, $file);//fwrite(): 写入文件

//    $ming = date("YmdHis".(time() % 200));

        fclose($resource);//fclose(): 关闭一个已经打开的文件指针
    }
    return $filename;
}

function mkdirs_1($path, $mode = 0777){
    if(is_dir($path)){
        return '无法创建,已经是目录了';
    }else{
        if(mkdir($path, $mode, true)) {
            return '创建成功';
        }else{
            return '创建失败';
        }
    }
}

//制作缩略图
function make_thumb($thumb_path,$save_path){
    $image = new \Think\Image();
    $image->open($thumb_path);
    $image->thumb(300, 300,\Think\Image::IMAGE_THUMB_FIXED)->save($save_path);
}

//存数据库(4张表)
function save_sql($data){
    $file_model = M('uploaded_file');
    $goods_image_model = M('goods_image');
    $goods_model = M('goods');
    $goods_spec_model = M('goods_spec');
    foreach ($data as $k => $v){
        $data_file = array(
            'store_id'=>$v['store_id'],
            'file_type'=>'image/jpeg',
            'file_name'=>$v['file_name'],
            'file_path'=>$v['file_path'],
            'add_time'=> time(),
            'belong'=>2,
            'item_id'=>$v['goods_id']
        );
        $res = $file_model->add($data_file);
        if(!$res){
            return false;
        }

        $data_image = array(
            'goods_id'=>$v['goods_id'],
            'image_url'=>$v['file_path'],
            'thumbnail'=>$v['thumb_path'],
            'file_id'=>$res
        );
        $res = $goods_image_model->add($data_image);
        if(!$res){
            return false; 
        }

        $data_goods = array(
            'default_image'=>$v['file_path'],
        );
        $res = $goods_model->where(array('goods_id'=>$v['goods_id']))->save($data_goods);
        if(!$res){
            return false;
        }

        foreach($data[$k]['spec'] as $key => $value){
            $data_goods_spec = array(
                'spec_1'=>$value['file_path'],
            );

            $res = $goods_spec_model->where(array('spec_id'=>$value['spec_id']))->save($data_goods_spec);

            if(!$res){
                return false;
            }
        }


    }
}

function _array_column($array=array(), $column_key, $index_key=null){
    $result = array();
    foreach($array as $arr) {
        if(!is_array($arr)) continue;

        if(is_null($column_key)){
            $value = $arr;
        }else{
            $value = $arr[$column_key];
        }

        if(!is_null($index_key)){
            $key = $arr[$index_key];
            $result[$key] = $value;
        }else{
            $result[] = $value;
        }
    }
    return $result;
}

function sync_data($url, $data_string) {
    $data_string = json_encode($data_string);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length: ' . strlen($data_string))
    );
    ob_start();
    $res = curl_exec($ch);
    if(!$res){
        return array('MessageCode'=>2, 'ErrorMsg'=>'同步失败');
    }else{
        return json_decode($res,true);
    }
    $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $return_content = ob_get_contents();
    ob_end_clean();

    return array('code'=>$return_code, 'result'=>$return_content);
}
